package hhm.android.machine.weight

import android.Manifest
import android.bluetooth.BluetoothAdapter
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.util.Log
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import androidx.activity.result.ActivityResultLauncher
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CircleCrop
import com.bumptech.glide.request.RequestOptions
import com.google.android.material.tabs.TabLayout
import com.loc.er
import com.tbruyelle.rxpermissions3.RxPermissions
import com.trello.rxlifecycle4.RxLifecycle
import com.trello.rxlifecycle4.android.ActivityEvent
import hhm.android.library.SwitchView
import hhm.android.library.bus.Bus
import hhm.android.library.tablayout.SegmentTabLayout
import hhm.android.library.tablayout.listener.OnTabSelectListener
import hhm.android.library.utils.GetStringListener
import hhm.android.library.utils.GlideUtils
import hhm.android.library.utils.OnMultiClickListener
import hhm.android.machine.R
import siau.android.base.*
import siau.android.http.model.DeviceIdModel
import siau.android.http.model.DeviceModel
import siau.android.http.model.UpdateDeviceInfoRequest
import siau.android.library.KeyString

@Route(path = WEIGHT_MACHINE_ROUTE)
class WeightMachineActivity : SBBaseActivity() {
    private val locationPermissions = arrayOf(
        Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION
    )
    lateinit var data: DeviceModel//接口返回的对象
    private val REQUEST_ENBLE_BT = 5555
    var bean: MyBlueToothBean? = null//本地蓝牙对象
    lateinit var stateTv: TextView
    lateinit var btn: TextView
    lateinit var machineName: TextView
    lateinit var machineNameLl: LinearLayout
    lateinit var voiceSwitch: SwitchView
    lateinit var shoeSizeSwitch: SwitchView
    lateinit var simpleVoiceSwitchIv: ImageView
    lateinit var simpleVoiceSwitchLl: LinearLayout
    private var simpleVoiceSwitch = false//false 未选中   true 选中
    lateinit var classSwitch: SwitchView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setTitleWhiteAndTextBlank()
        setContentView(R.layout.activity_weight_machine)

        stateTv = findViewById(R.id.activity_weight_machine_tv_state)
        btn = findViewById(R.id.activity_weight_machine_btn)

        voiceSwitch = findViewById(R.id.activity_weight_machine_voice)
        simpleVoiceSwitchIv = findViewById(R.id.activity_weight_machine_voice_simple_iv)
        simpleVoiceSwitchLl = findViewById(R.id.activity_weight_machine_voice_simple_ll)
        shoeSizeSwitch = findViewById(R.id.activity_weight_machine_shoe_size)
        classSwitch = findViewById(R.id.activity_weight_machine_class)
        machineName = findViewById(R.id.activity_weight_machine_name)
        machineNameLl = findViewById(R.id.activity_weight_machine_name_ll)

        if (SBApplication.userData.isCreator != 1) {
            btn.visibility = View.GONE
        }

        data = intent.getSerializableExtra(KeyString.data) as DeviceModel

        initTitleWithLine(data.productName)
        machineName.text = data.deviceName

        SBApplication.getBlueToothUtils()

        //检查蓝牙是否连接
        if (SBApplication.getBlueToothUtils().connectDevice?.size!! > 0) {
            checkNeedLoading()
        } else {
            if (SBApplication.getBlueToothUtils().mBluetoothAdapter == null) {
                showToast("当前设备不支持蓝牙")
                return
            }

            val rxPermissions = RxPermissions(this)
            rxPermissions.request(*locationPermissions).subscribe {
                if (it) {
                    // 没有打开蓝牙
                    if (!SBApplication.getBlueToothUtils().mBluetoothAdapter.isEnabled) {
                        val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
                        startActivityForResult(enableBtIntent, REQUEST_ENBLE_BT)
                    } else {
                        SBApplication.getBlueToothUtils().pairBlueTooth()
                    }
                } else {
                    showToast("蓝牙功能需要获取GPS位置权限才能扫描到设备")
                }
            }

        }

        btn.setOnClickListener(object : OnMultiClickListener() {
            override fun onMultiClick(v: View?) {
                getSureDialog(this@WeightMachineActivity, {
//                    if (SBApplication.startCalculate.value == true && SBApplication.calculateType == 1) {
//                        SBApplication.startCalculate.value = false
//                    }
                    showLoadingFragment(R.id.activity_weight_machine_fl)
                    val r = DeviceIdModel(data.deviceId)
                    HttpHelper().unbindDevice(r)?.compose(RxLifecycle.bindUntilEvent(lifecycle(), ActivityEvent.STOP))?.subscribe({
                        removeLoadingFragment()
                        showToast(getString(R.string.unbind_success))
                        if (bean != null) {
                            SBApplication.getBlueToothUtils().disConnect(bean)
                            SBApplication.getBlueToothUtils().connectDevice.remove(bean)
                        }
                        var removeBean: DeviceModel? = null
                        SBApplication.userData.deviceList?.forEach {
                            if (it.bluetoothCode == data.bluetoothCode) {
                                removeBean = it
                            }
                        }
                        if (removeBean != null) {
                            SBApplication.userData.deviceList?.remove(removeBean)
                        }
                        SBApplication.getBlueToothUtils().setControlCallback(null)
                        SBApplication.hasWeightMachine = false
                        SBApplication.hasHeightMachine = false
                        SBApplication.hasToothBrushMachine = false
                        SBApplication.userData.deviceList?.forEach { d ->
                            when (d.deviceType) {
                                1 -> {
                                    SBApplication.hasWeightMachine = true
                                }
                                2 -> {
                                    SBApplication.hasHeightMachine = true
                                }
                                3 -> {
                                    SBApplication.hasToothBrushMachine = true
                                }
                            }
                        }
                        ARouter.getInstance().build(MAIN_ROUTER).withFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK).navigation()
                    }, {
                        removeLoadingFragment()
                        showToast(it.message)
                    })
                }, content = getString(R.string.sure_delete_device), showTitle = false)
            }
        })
        machineNameLl.setOnClickListener(object : OnMultiClickListener() {
            override fun onMultiClick(v: View?) {
                if (SBApplication.userData.isCreator == 1) {
                    getStringDialog(this@WeightMachineActivity, getString(R.string.get_machine_name), "", object : GetStringListener {
                        override fun getString(s: String) {
                            showLoadingFragment(R.id.activity_weight_machine_fl)
                            val r = UpdateDeviceInfoRequest(data.deviceId, s)
                            HttpHelper().updateDeviceInfo(r)?.compose(RxLifecycle.bindUntilEvent(lifecycle(), ActivityEvent.STOP))?.subscribe({
                                removeLoadingFragment()
                                machineName.text = s
                            }, {
                                removeLoadingFragment()
                                showToast(it.message)
                            })
                        }
                    })
                }
            }
        })

        SBApplication.getBlueToothUtils().connectDeviceNum?.observe(this, {
            checkNeedLoading()
        })

        voiceSwitch.setOnClickCheckedListener {
            if (it) {
                showLoadingFragment(R.id.activity_weight_machine_fl)
                val getTrigger: ByteArray
                if (!voiceSwitch.isChecked) {
                    getTrigger = byteArrayOf(0xA7.toByte(), 0x00, 0x04, 0x02, 0x85.toByte(), 0x01, 0x8C.toByte(), 0x7A)
                    bean?.buttonStateChange = MyBlueToothBean.VoiceClose
                } else {
                    getTrigger = byteArrayOf(0xA7.toByte(), 0x00, 0x04, 0x02, 0x85.toByte(), 0x00, 0x8B.toByte(), 0x7A)
                    bean?.buttonStateChange = MyBlueToothBean.VoiceOpen
                }
                BlueToothUtil.getInstance().sendMsg(bean, getTrigger)
                handler.removeCallbacksAndMessages(null)
                handler.sendEmptyMessageDelayed(0, 5000)
            }
        }

        shoeSizeSwitch.setOnClickCheckedListener {
            if (it) {
                showLoadingFragment(R.id.activity_weight_machine_fl)
                val getTrigger: ByteArray
                if (!shoeSizeSwitch.isChecked) {
                    getTrigger = byteArrayOf(0xA7.toByte(), 0x00, 0x04, 0x03, 0x83.toByte(), 0x01, 0x1E, 0xA9.toByte(), 0x7A)
                    bean?.buttonStateChange = MyBlueToothBean.ShoeSizeClose
                } else {
                    getTrigger = byteArrayOf(0xA7.toByte(), 0x00, 0x04, 0x03, 0x83.toByte(), 0x00, 0x1E, 0xA8.toByte(), 0x7A)
                    bean?.buttonStateChange = MyBlueToothBean.ShoeSizeOpen
                }
                BlueToothUtil.getInstance().sendMsg(bean, getTrigger)
                handler.removeCallbacksAndMessages(null)
                handler.sendEmptyMessageDelayed(1, 5000)
            }
        }

        simpleVoiceSwitchIv.setOnClickListener(object : OnMultiClickListener() {
            override fun onMultiClick(v: View?) {
                showLoadingFragment(R.id.activity_weight_machine_fl)
                val getTrigger: ByteArray
                if (simpleVoiceSwitch) {
                    getTrigger = byteArrayOf(0xA7.toByte(), 0x00, 0x04, 0x02, 0x89.toByte(), 0x01, 0x90.toByte(), 0x7A)
                    bean?.buttonStateChange = MyBlueToothBean.SimpleVoiceClose
                } else {
                    getTrigger = byteArrayOf(0xA7.toByte(), 0x00, 0x04, 0x02, 0x89.toByte(), 0x00, 0x8F.toByte(), 0x7A)
                    bean?.buttonStateChange = MyBlueToothBean.SimpleVoiceOpen
                }
                BlueToothUtil.getInstance().sendMsg(bean, getTrigger)
                handler.removeCallbacksAndMessages(null)
                handler.sendEmptyMessageDelayed(2, 5000)
            }
        })

        classSwitch.setOnClickCheckedListener {
            if (it) {
                showLoadingFragment(R.id.activity_weight_machine_fl)
                val getTrigger: ByteArray
                if (!classSwitch.isChecked) {
                    getTrigger = byteArrayOf(0xA7.toByte(), 0x00, 0x04, 0x03, 0x81.toByte(), 0x00, 0x00, 0x88.toByte(), 0x7A)
                    bean?.buttonStateChange = MyBlueToothBean.classLBtoKG
                } else {
                    getTrigger = byteArrayOf(0xA7.toByte(), 0x00, 0x04, 0x03, 0x81.toByte(), 0x00, 0x06, 0x8E.toByte(), 0x7A)
                    bean?.buttonStateChange = MyBlueToothBean.classKGtoLB
                }
                BlueToothUtil.getInstance().sendMsg(bean, getTrigger)
                handler.removeCallbacksAndMessages(null)
                handler.sendEmptyMessageDelayed(3, 5000)
            }
        }
    }

    private fun checkNeedLoading() {
        bean = null
        SBApplication.getBlueToothUtils().connectDevice?.forEach {
            if (it.bluetoothCode.equals(data.bluetoothCode)) {
                bean = it
            }
        }
        if (bean == null) {
            stateTv.text = getString(R.string.unconnected)
            SBApplication.getBlueToothUtils().setControlCallback(null)
            voiceSwitch.setCanUse(false)
            simpleVoiceSwitchLl.visibility = View.GONE
            shoeSizeSwitch.setCanUse(false)
            classSwitch.setCanUse(false)
        } else {
            stateTv.text = getString(R.string.connected)
            SBApplication.getBlueToothUtils().setControlCallback(control)
            runOnUiThread {
                voiceSwitch.setChecked(bean!!.voiceTrigger, false)
                if (bean!!.simpleVoiceTrigger) {
                    simpleVoiceSwitchIv.setImageResource(R.drawable.ring_main_5)
                } else {
                    simpleVoiceSwitchIv.setImageResource(R.drawable.ring_ca_1)
                }
                shoeSizeSwitch.setChecked(bean!!.shoeSizeTrigger, false)
                classSwitch.setChecked(bean!!.classTrigger == 1, false)
            }
            voiceSwitch.setCanUse(true)
            if (voiceSwitch.isChecked) {
                simpleVoiceSwitchLl.visibility = View.VISIBLE
            } else {
                simpleVoiceSwitchLl.visibility = View.GONE
            }
            shoeSizeSwitch.setCanUse(true)
            classSwitch.setCanUse(true)
        }

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_ENBLE_BT && resultCode == RESULT_OK) {
            SBApplication.getBlueToothUtils().pairBlueTooth()
        } else if (requestCode == REQUEST_ENBLE_BT && resultCode != RESULT_OK) {
            showToast("请打开手机蓝牙后再试")
        }
    }

    private val control = object : BlueToothUtil.ControlCallBack {
        override fun voiceOpenSuccess(blueToothCode: String) {
            if (bean?.bluetoothCode == blueToothCode) {
                bean?.voiceTrigger = true
                runOnUiThread {
                    voiceSwitch.setChecked(true, false)
                    simpleVoiceSwitchLl.visibility = View.VISIBLE
                }
                removeLoadingFragment()
            }
        }

        override fun voiceCloseSuccess(blueToothCode: String) {
            if (bean?.bluetoothCode == blueToothCode) {
                bean?.voiceTrigger = false
                runOnUiThread {
                    voiceSwitch.setChecked(false, false)
                    simpleVoiceSwitchLl.visibility = View.GONE
                }
                removeLoadingFragment()
            }
        }

        override fun shoeSizeOpenSuccess(blueToothCode: String) {
            if (bean?.bluetoothCode == blueToothCode) {
                bean?.shoeSizeTrigger = true
                runOnUiThread {
                    shoeSizeSwitch.setChecked(true, false)
                }
                removeLoadingFragment()
            }
        }

        override fun shoeSizeCloseSuccess(blueToothCode: String) {
            if (bean?.bluetoothCode == blueToothCode) {
                bean?.shoeSizeTrigger = false
                runOnUiThread {
                    shoeSizeSwitch.setChecked(false, false)
                }
                removeLoadingFragment()
            }
        }

        override fun simpleVoiceOpenSuccess(blueToothCode: String) {
            if (bean?.bluetoothCode == blueToothCode) {
                bean?.simpleVoiceTrigger = true
                runOnUiThread {
                    simpleVoiceSwitch = true
                    simpleVoiceSwitchIv.setImageResource(R.drawable.ring_main_5)
                }
                removeLoadingFragment()
            }
        }

        override fun simpleVoiceCloseSuccess(blueToothCode: String) {
            if (bean?.bluetoothCode == blueToothCode) {
                bean?.simpleVoiceTrigger = false
                runOnUiThread {
                    simpleVoiceSwitch = false
                    simpleVoiceSwitchIv.setImageResource(R.drawable.ring_ca_1)
                }
                removeLoadingFragment()
            }
        }

        override fun classCMtoFTSuccess(blueToothCode: String) {
            if (bean?.bluetoothCode == blueToothCode) {
                removeLoadingFragment()
            }
        }

        override fun classFTtoCMSuccess(blueToothCode: String) {
            if (bean?.bluetoothCode == blueToothCode) {
                removeLoadingFragment()
            }
        }

        override fun classLBtoKGSuccess(blueToothCode: String) {
            if (bean?.bluetoothCode == blueToothCode) {
                bean?.classTrigger = 0
                runOnUiThread {
                    classSwitch.setChecked(false, false)
                }
                removeLoadingFragment()
            }
        }

        override fun classKGtoLBSuccess(blueToothCode: String) {
            if (bean?.bluetoothCode == blueToothCode) {
                bean?.classTrigger = 1
                runOnUiThread {
                    classSwitch.setChecked(true, false)
                }
                removeLoadingFragment()
            }
        }
    }

    override fun onBackPressed() {
        if (findLoadingFragment() != null) {
            removeLoadingFragment()
        } else {
            SBApplication.getBlueToothUtils().setControlCallback(null)
            super.onBackPressed()
        }
    }

    var handler = object : Handler() {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            when (msg.what) {
                0 -> {
                    if (bean?.buttonStateChange != MyBlueToothBean.ButtonDefault) {
                        removeLoadingFragment()
                        showToast("切换失败，请稍后尝试哦～")
                        if (bean?.buttonStateChange == MyBlueToothBean.VoiceOpen) {
                            bean?.voiceTrigger = false
                            runOnUiThread {
                                voiceSwitch.setChecked(false, false)
                            }
                        } else if (bean?.buttonStateChange == MyBlueToothBean.VoiceClose) {
                            bean?.voiceTrigger = true
                            runOnUiThread {
                                voiceSwitch.setChecked(true, false)
                            }
                        }
                    }
                }
                1 -> {
                    if (bean?.buttonStateChange != MyBlueToothBean.ButtonDefault) {
                        removeLoadingFragment()
                        showToast("切换失败，请稍后尝试哦～")
                        if (bean?.buttonStateChange == MyBlueToothBean.ShoeSizeOpen) {
                            bean?.shoeSizeTrigger = false
                            runOnUiThread {
                                shoeSizeSwitch.setChecked(false, false)
                            }
                        } else if (bean?.buttonStateChange == MyBlueToothBean.ShoeSizeClose) {
                            bean?.shoeSizeTrigger = true
                            runOnUiThread {
                                shoeSizeSwitch.setChecked(true, false)
                            }
                        }
                    }
                }
                2 -> {
                    if (bean?.buttonStateChange != MyBlueToothBean.ButtonDefault) {
                        removeLoadingFragment()
                        showToast("切换失败，请稍后尝试哦～")
                        if (bean?.buttonStateChange == MyBlueToothBean.SimpleVoiceOpen) {
                            bean?.simpleVoiceTrigger = false
                            runOnUiThread {
                                simpleVoiceSwitch = false
                            }
                        } else if (bean?.buttonStateChange == MyBlueToothBean.SimpleVoiceClose) {
                            bean?.simpleVoiceTrigger = true
                            runOnUiThread {
                                simpleVoiceSwitch = true
                            }
                        }
                    }
                }
                3 -> {
                    if (bean?.buttonStateChange != MyBlueToothBean.ButtonDefault) {
                        removeLoadingFragment()
                        showToast("切换失败，请稍后尝试哦～")
                        if (bean?.buttonStateChange == MyBlueToothBean.classKGtoLB) {
                            bean?.classTrigger = 0
                            runOnUiThread {
                                classSwitch.setChecked(false, false)
                            }
                        } else if (bean?.buttonStateChange == MyBlueToothBean.classLBtoKG) {
                            bean?.classTrigger = 1
                            runOnUiThread {
                                classSwitch.setChecked(true, false)
                            }
                        }
                    }
                }
            }

        }
    }
}